// import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJSX from '@vitejs/plugin-vue-jsx'
import { resolve } from 'path'
import styleImport from 'vite-plugin-style-import'
import fs from 'fs'
import dotenv from 'dotenv'
import type { UserConfig, ConfigEnv } from 'vite'
import { generateModifyVars } from './src/styles/theme/generateModifyVars'
// import { configThemePlugin } from './src/styles/plugin/theme'

function pathResolve(dir: string) {
  return resolve(process.cwd(), './', dir)
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const isBuild = command === 'build'
  console.log(isBuild)

  try {
    // 根据环境变量加载环境变量文件
    const file = dotenv.parse(fs.readFileSync(`.env.${mode}`))
    // 根据获取的key给对应的环境变量赋值
    for (const key of Object.keys(file)) {
      process.env[key] = file[key]
    }
  } catch (e) {
    console.error(e)
  }
  return {
    plugins: [
      vue(),
      vueJSX(),
      styleImport({
        libs: [
          {
            libraryName: 'ant-design-vue',
            esModule: true,
            resolveStyle: (name) => {
              return `ant-design-vue/es/${name}/style/index`
            }
          }
        ]
      })
      // configThemePlugin(isBuild)
    ],
    resolve: {
      alias: [
        { find: '@', replacement: pathResolve('src') },
        { find: 'public', replacement: pathResolve('public') }
      ]
    },
    css: {
      preprocessorOptions: {
        // 引入公用的样式
        scss: {
          additionalData: ['@import "@/styles/common.scss";']
        },
        less: {
          modifyVars: generateModifyVars(),
          javascriptEnabled: true
        }
      }
    },
    base: './', //打包路径
    // 打包配置
    build: {
      target: 'modules',
      outDir: 'dist', //指定输出路径
      assetsDir: 'assets', // 指定生成静态资源的存放路径
      minify: 'terser' // 混淆器，terser构建后文件体积更小
    },
    server: {
      port: 3000, //启动端口
      open: true,
      proxy: {
        '/api': {
          // target: 'http://29135jo738.zicp.vip/api/v1',
          target: process.env['VITE_APP_API_URL'],
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      },
      cors: true
    }
  }
}

// https://vitejs.dev/config/
// export default defineConfig({})
